package com.service.system.businessShop.impl;

import com.dao.*;
import com.entity.OrderVo;
import com.entity.system.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.service.system.businessShop.BusinessShopService;
import com.util.Const;
import com.util.HttpClientUtil;
import com.util.LogUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class BusinessShopServiceImpl implements BusinessShopService{

    @Autowired
    BusinessShopMapper businessShopMapper;

    @Autowired
    BusinessShopTempMapper businessShopTempMapper;

    @Autowired
    UserAuthenticationMapper userAuthenticationMapper;

    @Autowired
    UserAuthenticationTempMapper userAuthenticationTempMapper;

    @Autowired
    UserInfoMapper userInfoMapper;

    @Autowired
    HatProvinceMapper hatProvinceMapper;

    @Autowired
    HatCityMapper hatCityMapper;

    @Autowired
    HatAreaMapper hatAreaMapper;

    @Autowired
    SystemMessageMapper systemMessageMapper;

    @Autowired
    SystemGlobalConfigMapper systemGlobalConfigMapper;

    @Autowired
    UserIncomeAwardMapper userIncomeAwardMapper;

    @Autowired
    UserAssetsMapper userAssetsMapper;

    @Autowired
    UserCashFlowMapper userCashFlowMapper;

    @Autowired
    TaskHistoryMapper taskHistoryMapper;

    @Autowired
    TaskConfigMapper taskConfigMapper;

    @Autowired
    ClassifyMapper classifyMapper;

    @Autowired
    OrderMapper orderMapper;


    @Override
    public Map<String, Object> findBusinessShopList(Map<String,Object> map1) {
        Map<String,Object> map = new HashMap<String,Object>();
        int pageNum = 1;
        int pageSize = 10;
        if(StringUtils.isNotEmpty(map1.get("pageNum").toString())){
            pageNum = Integer.parseInt(map1.get("pageNum").toString());
        }
        if(StringUtils.isNotEmpty(map1.get("pageSize").toString())){
            pageSize = Integer.parseInt(map1.get("pageSize").toString());
        }
        if(null != map1.get("phone")){
            UserInfo userInfo = userInfoMapper.findUserByPhone(map1.get("phone").toString());
            map1.put("userId",userInfo.getId());
        }
        AgentNew agentNew = (AgentNew) map1.get("an");
        if(null != agentNew){

            if(agentNew.getAgentLevel() == 1){
                String area = hatAreaMapper.findByAreaId(agentNew.getCountyCode()).getArea();
                String city = hatCityMapper.findByCityId(agentNew.getCityCode()).getCity();
                String province = hatProvinceMapper.findByProvinceId(agentNew.getProvinceCode()).getProvince();
                map1.put("area",area.substring(0,area.length()-1)+"%");
                map1.put("city",city.substring(0,city.length()-1)+"%");
                map1.put("province",province.substring(0,province.length()-1)+"%");
            }else if(agentNew.getAgentLevel() == 2){
                String city = hatCityMapper.findByCityId(agentNew.getCityCode()).getCity();
                String province = hatProvinceMapper.findByProvinceId(agentNew.getProvinceCode()).getProvince();
                map1.put("city",city.substring(0,city.length()-1)+"%");
                map1.put("province",province.substring(0,province.length()-1)+"%");
            }else if(agentNew.getAgentLevel() == 3){
                String province = hatProvinceMapper.findByProvinceId(agentNew.getProvinceCode()).getProvince();
                map1.put("province",province.substring(0,province.length()-1)+"%");
            }
            map1.put("certificationType",2);
//            List<Long> userIds = userAuthenticationMapper.findUserIdByMap(map);
//            if(userIds.size() > 0){
//                map1.put("userIds",userIds);
//            }else {
//                map.put("code",Const.SUCCESS_CODE);
//                map.put("message","暂无数据");
//                return map;
//            }


        }
        PageHelper.startPage(pageNum,pageSize);
        List<BusinessShopTemp> list = new ArrayList<>();
        if(null == map1.get("state")){
            list = businessShopTempMapper.findByMapMerge(map1);
        }else {

            list = businessShopTempMapper.findByMap(map1);
        }

        PageInfo<BusinessShopTemp> pageInfo = new PageInfo<BusinessShopTemp>(list);
        for(BusinessShopTemp bs : list){
            UserInfo userInfo = userInfoMapper.findUserById(bs.getUserId());
            if(null != userInfo){
                bs.setPhone(userInfo.getPhone());
                bs.setNickName(userInfo.getNickName());
            }
        }
        map.clear();
        map.put("code", Const.SUCCESS_CODE);
        map.put("message","查询成功");
        map.put("businessShops",list);
        map.put("page",pageInfo);
        return map;
    }

    @Override
    @Transactional
    public Map<String, Object> auditBus(String id, String auditType, String content) {
        Map<String,Object> map = new HashMap<>();
        BusinessShopTemp businessShopTemp = businessShopTempMapper.selectByPrimaryKey(Long.parseLong(id));
        if(null == businessShopTemp){
            map.put("code",Const.ERROR_CODE);
            map.put("message","审核失败");
            return map;
        }
        businessShopTemp.setModifyTime(new Date());
        if("1".equals(auditType)){  //审核通过
            businessShopTemp.setState(1);
            businessShopTemp.setRemark(content);
            int num = businessShopTempMapper.updateByPrimaryKeySelective(businessShopTemp);
            if(num == 1){
                map.put("userId",businessShopTemp.getUserId());
                BusinessShop businessShop = businessShopMapper.findByMap(map);

                map.clear();
                UserAuthentication userAuthentication = userAuthenticationMapper.findByUserId(businessShopTemp.getUserId());
                businessShopTemp.setId(null);

                if(null != userAuthentication){
                    businessShopTemp.setBusinessId(userAuthentication.getId());
                }
                int num1 = 0;
                if(null == businessShop){
                    businessShop = new BusinessShop();
                    BeanUtils.copyProperties(businessShopTemp,businessShop,new String[]{"id"});
                    num1 = businessShopMapper.insertSelective(businessShop);
                }else {
                    BeanUtils.copyProperties(businessShopTemp,businessShop,new String[]{"id"});
                    num1 = businessShopMapper.updateByPrimaryKeySelective(businessShop);
                }
                if(num1 == 1){
                    // 写系统消息
                    SystemMessage systemMessage = new SystemMessage();
                    systemMessage.setContent(businessShop.getRemark());
                    systemMessage.setUserId(businessShop.getUserId());
                    systemMessage.setCreateTime(new Date());
                    num1 = systemMessageMapper.insert(systemMessage);
                    if(num1 == 1){
                        map.put("code",Const.SUCCESS_CODE);
                        map.put("message","审核成功");
                    }
                }else {
                    map.put("code",Const.ERROR_CODE);
                    map.put("message","审核失败");
                }
            }else {
                map.put("code",Const.ERROR_CODE);
                map.put("message","审核失败");
            }
        }else {  //审核不通过
            businessShopTemp.setState(2);
            businessShopTemp.setRemark(content);
            int num = businessShopTempMapper.updateByPrimaryKeySelective(businessShopTemp);
            if(num == 1){
                // 写系统消息
                SystemMessage systemMessage = new SystemMessage();
                systemMessage.setContent(content);
                systemMessage.setUserId(businessShopTemp.getUserId());
                systemMessage.setCreateTime(new Date());
                int num1 = systemMessageMapper.insertSelective(systemMessage);
                if(num1 == 1){
                    map.put("code",Const.SUCCESS_CODE);
                    map.put("message","审核成功");
                }else {
                    map.put("code",Const.ERROR_CODE);
                    map.put("message","审核失败");
                }
            }else {
                map.put("code",Const.ERROR_CODE);
                map.put("message","审核失败");
            }
        }
        return map;
    }

    @Override
    public Map<String, Object> findMerchantsList(String pageSize, String pageNum, String state, String isPreferredBusiness, String label, AgentNew agentNew,String startTime,String endTime,String phone) {
        Map<String,Object> map = new HashMap<String,Object>();
        if(StringUtils.isEmpty(pageNum)){
            pageNum = "1";
        }
        if(StringUtils.isEmpty(pageSize)){
            pageSize = "10";
        }
        if(StringUtils.isNotEmpty(state)){
            map.put("state",state);
        }
        if(StringUtils.isNotEmpty(isPreferredBusiness)){
            map.put("isPreferredBusiness",isPreferredBusiness);
        }
        if(StringUtils.isNotEmpty(label) && !"0".equals(label)){
            map.put("label",label);
        }
        if(StringUtils.isNotEmpty(startTime)){
            map.put("startTime",startTime);
        }
        if(StringUtils.isNotEmpty(endTime)){
            map.put("endTime",endTime);
        }
        if(StringUtils.isNotEmpty(phone)){
            UserInfo userInfo = userInfoMapper.findUserByPhone(phone);
            if(null == userInfo){
                map.clear();
                map.put("code",Const.ERROR_CODE);
                map.put("message","该用户不存在");
                return map;
            }else {
                map.put("userId",userInfo.getId());
            }
        }
        if(null != agentNew){

            if(agentNew.getAgentLevel() == 1){
                String area = hatAreaMapper.findByAreaId(agentNew.getCountyCode()).getArea();
                String city = hatCityMapper.findByCityId(agentNew.getCityCode()).getCity();
                String province = hatProvinceMapper.findByProvinceId(agentNew.getProvinceCode()).getProvince();
                map.put("area",area.substring(0,area.length()-1)+"%");
                map.put("city",city.substring(0,city.length()-1)+"%");
                map.put("province",province.substring(0,province.length()-1)+"%");
            }else if(agentNew.getAgentLevel() == 2){
                String city = hatCityMapper.findByCityId(agentNew.getCityCode()).getCity();
                String province = hatProvinceMapper.findByProvinceId(agentNew.getProvinceCode()).getProvince();
                map.put("city",city.substring(0,city.length()-1)+"%");
                map.put("province",province.substring(0,province.length()-1)+"%");
            }else if(agentNew.getAgentLevel() == 3){
                String province = hatProvinceMapper.findByProvinceId(agentNew.getProvinceCode()).getProvince();
                map.put("province",province.substring(0,province.length()-1)+"%");
            }
        }
        map.put("certificationType",2);
        PageHelper.startPage(Integer.parseInt(pageNum),Integer.parseInt(pageSize));
        List<UserAuthenticationTemp> list = userAuthenticationTempMapper.findByMapMerge(map);
//        if(StringUtils.isEmpty(state)){
//            list = userAuthenticationTempMapper.findByMapMerge(map);
//        }else {
//            list = userAuthenticationTempMapper.findUserAuthenticationTempByMap(map);
//        }

        PageInfo<UserAuthenticationTemp> pageInfo = new PageInfo<>(list);
        List<UserAuthenticationTemp> authenticationTemps = pageInfo.getList();
        for(UserAuthenticationTemp authenticationTemp : authenticationTemps){
            authenticationTemp.setPhone(userInfoMapper.findPhoneByUserId(authenticationTemp.getUserId()));
            if(null != authenticationTemp.getAuditUserId()){
                UserInfo userInfo = userInfoMapper.findUserById(authenticationTemp.getAuditUserId());
                if(null != userInfo){
                    authenticationTemp.setAuditUserName(userInfo.getNickName());
                }
            }
        }
        map.clear();
        map.put("code",Const.SUCCESS_CODE);
        map.put("message","查询成功");
        map.put("page",pageInfo);
        map.put("authenticationTemps",authenticationTemps);
        return map;
    }

    @Override
    public Map<String, Object> findBusinessShopByUserId(String userId) {
        Map<String,Object> map = new HashMap<String, Object>();
        BusinessShop businessShop = businessShopMapper.findBusinessShopByUserId(Long.parseLong(userId));
        if(null != businessShop){
            map.put("code",Const.SUCCESS_CODE);
            map.put("message","查询成功");
            map.put("businessShop",businessShop);
        }else {
            map.put("code",Const.ERROR_CODE);
            map.put("message","查无数据");
        }
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> merchantsAudit(String id, String type,String content) {
        Map<String,Object> map = new HashMap<>();
        int num = 0;
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        UserInfo userInfo = (UserInfo) session.getAttribute(Const.SESSION_USER);
        //审核通过
        if("1".equals(type)){
            //临时表数据
            UserAuthenticationTemp authenticationTemp = userAuthenticationTempMapper.selectByPrimaryKey(Long.parseLong(id));
            authenticationTemp.setState((byte) 2);
            authenticationTemp.setModifyTime(new Date());
            authenticationTemp.setAuditTime(new Date());
            authenticationTemp.setAuditUserId(userInfo.getId());
            UserAuthentication authentication = new UserAuthentication();
            BeanUtils.copyProperties(authenticationTemp,authentication);
            authentication.setAuditTime(new Date());
            //正式表数据
            UserAuthentication userAuthentication = userAuthenticationMapper.findByUserId(authenticationTemp.getUserId());
            //如果正式表有数据 修改  否则 新增
            if(null != userAuthentication){
                //修改正式表
                num = userAuthenticationMapper.updateByUserId(authentication);
                if(num == 1){
                    //修改临时表
                    num = userAuthenticationTempMapper.updateByPrimaryKeySelective(authenticationTemp);
                }
            }else {
                //新增正式表数据
                num = userAuthenticationMapper.insertSelective(authentication);
                if(num == 1){
                    //修改临时表
                    num = userAuthenticationTempMapper.updateByPrimaryKeySelective(authenticationTemp);
                }
            }
            /*调用商城添加商户业务(认证为商户时调用)*/
            if(authentication.getCertificationType() == 2){
                ResourceBundle rs = ResourceBundle.getBundle("environment");
                //创建参数队列
                List<NameValuePair> formparams = new ArrayList<NameValuePair>();
                formparams.add(new BasicNameValuePair("operatorId", String.valueOf(authentication.getId())));
                formparams.add(new BasicNameValuePair("sellerName", authentication.getBusinessAbbreviation()));
                formparams.add(new BasicNameValuePair("sellerType", "1"));
                formparams.add(new BasicNameValuePair("runningStatus", "1"));
                String url = rs.getString( "shopping.admin.url" ) + "/seller/editSeller.do";
                try {
                    UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
                    String httpResult = HttpClientUtil.post(url, "addSeller", uefEntity);
                    LogUtil.info("调用商城(admin)添加商户接口返回信息:" + httpResult);
                } catch (Exception e) {
                    LogUtil.error("调用商城(admin)添加商户接口错误信息:" + ExceptionUtils.getStackTrace(e));
                }
            }

            if (num == 1) {
                SystemMessage systemMessage = new SystemMessage();
                systemMessage.setCreateTime(new Date());
                systemMessage.setUserId(authentication.getUserId());
                if (authentication.getCertificationType() == 1) {
                    systemMessage.setContent("恭喜您，已经通过了个人认证审核。");
                } else {
                    systemMessage.setContent("恭喜您，已经通过了商户认证审核，快去创建您的主页吧。");
                }
                // 发送系统消息
                num = systemMessageMapper.insertSelective(systemMessage);
            }

            if(num == 1){
                //认证返现
                authenticationAward(authentication.getUserId());
                /* 完成身份认证 */
                LogUtil.info("个人信息已经完善，需要完成任务----------用户名：[{}]"+ authentication.getUserId());
                try {
                    shareApp(authentication.getUserId(), (long) 10);
                } catch (ParseException e) {
                    e.printStackTrace();
                    LogUtil.error("插入完成身份认证任务报错");
                    map.put("code",Const.ERROR_CODE);
                    map.put("message","审核失败");
                    return map;
                }
                //商户认证
                if(authentication.getCertificationType() == 2){
                    updateInviteBusinessTaskState(authentication.getUserId());
                }
            }
        }else { //审核不通过
            LogUtil.info("content:" + content + ", id : " + id);
            //临时表数据
            UserAuthenticationTemp authenticationTemp = userAuthenticationTempMapper.selectByPrimaryKey(Long.parseLong(id));
            if(null == authenticationTemp){
                LogUtil.info("**********临时表数据为空*************");
                map.put("code",Const.ERROR_CODE);
                map.put("message","审核失败");
                return map;
            }
            //正式表数据
            UserAuthentication userAuthentication = userAuthenticationMapper.findByUserId(authenticationTemp.getUserId());

            if(userAuthentication != null){
                BeanUtils.copyProperties(userAuthentication, authenticationTemp);//用正式认证信息覆盖临时认证信息
                userAuthentication.setAuditTime(new Date());
                userAuthentication.setAuditUserId(userInfo.getId());
                userAuthentication.setState((byte) 3);
                num = userAuthenticationMapper.updateByUserId(userAuthentication);
            }
            authenticationTemp.setState((byte) 3);//审核失败
            authenticationTemp.setModifyTime(new Date());
            authenticationTemp.setId(Long.parseLong(id));//防止临时表和正式表id不一样的情况
            authenticationTemp.setAuditTime(new Date());
            authenticationTemp.setAuditUserId(userInfo.getId());
            num = userAuthenticationTempMapper.updateByPrimaryKeySelective(authenticationTemp);
            if(num == 1){
                SystemMessage message = new SystemMessage();
                message.setContent(content);
                message.setCreateTime(new Date());
                message.setUserId(authenticationTemp.getUserId());
                num = systemMessageMapper.insertSelective(message);

            }

        }
        map.put("code",Const.SUCCESS_CODE);
        map.put("message","审核成功");
        return map;
    }

    /**
     * 认证返现
     */
    public void authenticationAward(Long userId){
        UserAuthentication userAuthentication = userAuthenticationMapper.findByUserId(userId);
        // 有这个配置说明有认证商户返现功能，否则不进入返现逻辑
        Map<String,Object> map = new HashMap<>();
        map.put("configKey","client.business.register.award");
        map.put("state",1);
        SystemGlobalConfig sysConfig = systemGlobalConfigMapper.findByMap(map);
        if(null != userAuthentication){
            Map<String,Object> recordMap = new HashMap<>();
            recordMap.put("userId", userId);
            recordMap.put("awardType", 1);
            recordMap.put("eventId", userAuthentication.getId());
            UserIncomeAward userIncomeAward = userIncomeAwardMapper.selectModel(recordMap);
            if(userIncomeAward != null){
                //说明之前返现过直接返回
                LogUtil.info("用户id : " + userId + "已经返现过，不再返现");
                return ;
            }
            if(null != sysConfig){
                Integer awards = sysConfig.getConfigNormal();// 奖励值
                Date awardStart = sysConfig.getCreateTime();// 奖励开始时间

                if (userAuthentication.getCreateTime().after(awardStart)) {// 首次认证成功时间必须在活动开始时间之后
                    UserAssets userAssets = userAssetsMapper.findUserAssetsByUserId(userAuthentication.getUserId());
                    userAssets.setAdvertCoin(userAssets.getAdvertCoin()+awards);
                    int awardFlag = userAssetsMapper.updateByPrimaryKeySelective(userAssets);

                    if (awardFlag == 1) {

                        UserIncomeAward award = new UserIncomeAward();
                        award.setUserId(userAuthentication.getUserId());
                        award.setEventId(userAuthentication.getId());
                        award.setAmount(awards);
                        award.setAwardType(1); // 1:代表认证返现活动
                        award.setCreateTime(new Date());
                        long id = userIncomeAwardMapper.insertSelective(award);
                        LogUtil.info("商户 ： " + userAuthentication.getBusinessAbbreviation() + " 得到 认证返现广告币" + awards);

                        //流水添加
                        UserCashFlow userCashFlow = new UserCashFlow();
                        userCashFlow.setPrice(new BigDecimal(Math.abs(awards)));
                        userCashFlow.setCreateTime(new Date());
                        userCashFlow.setCashFlowDirection((byte) 1);
                        userCashFlow.setUserId(userId);
                        userCashFlow.setCashFlowTitle((byte) 5); //活动奖励
                        userCashFlow.setTriggerTableName("tb_user_income_award");
                        userCashFlow.setTriggerNo(id+"");
                        userCashFlow.setBalance(new BigDecimal(userAssets.getAdvertCoin()));
                        userCashFlow.setCashFlowType((byte) 2); //广告币
                        userCashFlowMapper.insertSelective(userCashFlow);
                        //流水添加end

                    } else {
                        LogUtil.error("商户 ： " + userAuthentication.getBusinessAbbreviation() + "返现失败！");
                    }
                }
            }
        }
    }

    public void shareApp(Long userId, Long taskConfigId) throws ParseException {
        if (userId == null || taskConfigId == null) {
            return;
        }
        Map<String, Object> taskHistoryMap = new HashMap<String, Object>();
        taskHistoryMap.put("userId", userId);
        taskHistoryMap.put("taskConfigId", taskConfigId);
        TaskHistory taskHistory = taskHistoryMapper.findByMap(taskHistoryMap);

        // 如果用户为null，就先给用户初始化一条数据
        if (taskHistory == null) {
            taskHistory = new TaskHistory();
            taskHistory.setCount(0);
            taskHistory.setUserId(userId);
            taskHistory.setTaskConfigId(taskConfigId);
            taskHistory.setIsFinish((byte) 2);
            taskHistory.setFinishTaskDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("1970-01-01 19:00:00"));
            taskHistoryMapper.insert(taskHistory);
        }

        // 是否是一次性任务
        TaskConfig taskConfig = taskConfigMapper.selectByPrimaryKey(taskConfigId);
        Boolean isOnceTask;
        if(null == taskConfig){
            LogUtil.info("**********任务没有配置**************");
            isOnceTask = false;
        }else {
            isOnceTask = taskConfig.getIsRepeat() == 0 ? true : false;
        }

        if (isOnceTask && taskHistory.getIsFinish() == 0) {
            // 一一次性任务
            return;
        }

        // 如果当前天已经做了任务，就不能再次做
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (sdf.format(new Date()).equals(sdf.format(taskHistory.getFinishTaskDate()))) {
            return;
        }

        Map<String, Object> taskConfigMap = new HashMap<String, Object>();
        taskConfigMap.put("id", taskConfigId);
        TaskConfig taskConfig1 = taskConfigMapper.findByMap(taskConfigMap);
        if (taskConfig1 == null) {
            return;
        }
        Integer taskCount = taskConfig1.getCount();

        // 任务数是1 只要大于2就表示任务完成
        if (taskHistory.getCount() + 1 >= taskCount) {
            taskHistory.setUserId(userId);
            taskHistory.setIsFinish((byte) 1);
            taskHistory.setCount(taskHistory.getCount() + 1);
            taskHistory.setFinishTaskDate(new Date());
            taskHistoryMapper.updateByUidAndTaskConId(taskHistory);
        } else if (taskHistory.getCount() + 1 < taskCount) {
            taskHistory.setCount(taskHistory.getCount() + 1);
            taskHistoryMapper.updateByUidAndTaskConId(taskHistory);
        }
    }

    public boolean updateInviteBusinessTaskState(Long userId) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        LogUtil.info("判断用户:[" + userId + "]商户审核");

        Map<String,Object> map = new HashMap<>();
        map.put("userId", userId);

        UserInfo user = userInfoMapper.findUserById(userId);//当前正在审核的商户的邀请人
        if(user != null){
            int type = 0;//任务类型  0：所有用户任务   1：合伙人任务  2：创客任务
            String role = user.getRole();
            if(role.equals("CHUANG")){
                type = 2;
            }else if(role.equals("HEHUOREN")){
                type = 1;
            }else if(role.equals("SERVER")){
                type = 1;
            }else{
                //TODO
            }

            map.clear();
            map.put("taskCode", "invite_first_auth_task"); //创客或合伙人邀请商户认证并通过审核任务code
            map.put("type", type);
            List<TaskConfig> cfgs = taskConfigMapper.findListByMap(map);
            TaskConfig tcfg = cfgs != null && cfgs.size() > 0 ? cfgs.get(0) : null;
            if(tcfg != null){
                boolean isCompleteTask = false;
                String currDateStr = format.format(new Date());//当前时间字符 2018-01-29
                map.clear();
                map.put("userId", user.getId());
                map.put("taskConfigId", tcfg.getId());
                TaskHistory taskHistory = taskHistoryMapper.findByMap(map);
                if(taskHistory != null){
                    if(format.format(taskHistory.getFinishTaskDate()).equals(currDateStr)){//如果是同一天
                        isCompleteTask = false;
                        taskHistory.setCount(taskHistory.getCount() + 1);
                    }else{
                        taskHistory.setCount(1);
                    }

                    boolean firstCompleteTask = false;
                    if(taskHistory.getIsFinish() != 1){
                        if(tcfg.getCount() >= taskHistory.getCount()){
                            taskHistory.setIsFinish((byte)1);
                            firstCompleteTask = true;
                        }else if(tcfg.getCount() < taskHistory.getCount()){
                            //TODO
                        }else{
                            taskHistory.setIsFinish((byte)0);
                        }
                    }

                    taskHistory.setFinishTaskDate(new Date());
                    int num = taskHistoryMapper.updateByPrimaryKeySelective(taskHistory);
                    if(num == 1 && firstCompleteTask){
                        isCompleteTask = true;
                    }
                }else{
                    taskHistory = new TaskHistory();
                    boolean firstCompleteTask = false;
                    if(tcfg.getCount() == 1){
                        taskHistory.setIsFinish((byte)1);
                        firstCompleteTask = true;
                    }else{
                        taskHistory.setIsFinish((byte)0);
                    }
                    taskHistory.setUserId(user.getId());
                    taskHistory.setCount(1);
                    taskHistory.setTaskConfigId(tcfg.getId());
                    taskHistory.setFinishTaskDate(new Date());
                    int num = taskHistoryMapper.insert(taskHistory);
                    if(num == 1 && firstCompleteTask){
                        isCompleteTask = true;
                    }
                }

                if(isCompleteTask){//完成任务
                    UserAssets uAssets = userAssetsMapper.findUserAssetsByUserId(user.getId());
                    uAssets.setTaskAwardBalance(uAssets.getTaskAwardBalance() + tcfg.getGrowthPoint());
                    uAssets.setModifyTime(new Date());
                    int num = userAssetsMapper.updateByPrimaryKeySelective(uAssets);
                    if(num == 1){
                        //完成任务发放奖励金流水
                        addUserCashFlowAsyn(Double.parseDouble(tcfg.getGrowthPoint()+""),(byte)1,user.getId(),26,"tb_user_assets",uAssets.getId(),new Double(uAssets.getTaskAwardBalance()),(byte)4);
                    }
                    return true;
                }
            }
        }

        return false;
    }

    public void addUserCashFlowAsyn(Double price, Byte direction,Long userId,Integer cashFlowtitle,String relatedTableName,Long relatedTableId,Double latestBalance,Byte cashFlowType) {

        final UserCashFlow cashFlow = new UserCashFlow();
        cashFlow.setPrice(new BigDecimal(price.intValue()));
        cashFlow.setCreateTime(new Date());
        cashFlow.setCashFlowDirection(direction);
        cashFlow.setUserId(userId);
        cashFlow.setCashFlowTitle(cashFlowtitle.byteValue());
        cashFlow.setTriggerTableName(relatedTableName);
        cashFlow.setTriggerNo(relatedTableId+"");
        cashFlow.setBalance(new BigDecimal(latestBalance.doubleValue()));
        cashFlow.setCashFlowType(cashFlowType);
        cashFlow.setVisible(1);
        cashFlow.setIsSuccess(1);
        //匿名内部类实现异步调用
        new Thread(){
            @Override
            public void run() {
                userCashFlowMapper.insert(cashFlow);
            }

        }.start();


    }

    @Override
    public Map<String, Object> findClassifyList(Map<String, Object> map) {
        Map<String,Object> map1 = new HashMap<>();
        int pageSize = 10;
        int pageNum = 1;
        if(StringUtils.isNotEmpty(map.get("pageSize").toString())){
            pageSize = Integer.parseInt(map.get("pageSize").toString());
        }
        if(StringUtils.isNotEmpty(map.get("pageNum").toString())){
            pageNum = Integer.parseInt(map.get("pageNum").toString());
        }
        PageHelper.startPage(pageNum,pageSize);
        List<Classify> classifies = classifyMapper.findByMap(map);
        PageInfo<Classify> pageInfo = new PageInfo<>(classifies);
        map1.put("code",Const.SUCCESS_CODE);
        map1.put("message","查询成功");
        map1.put("page",pageInfo);
        map1.put("classifies",pageInfo.getList());
        return map1;
    }

    @Override
    public Map<String, Object> addClassify(Classify classify) {
        Map<String,Object> map = new HashMap<>();
        map.put("label",classify.getLabel());
        List<Classify> list = classifyMapper.findByMap(map);
        map.clear();
        if(list.size() > 0){
            map.put("code",Const.ERROR_CODE);
            map.put("message","分类编号已存在");
            return map;
        }
        classify.setCreateTime(new Date());
        int num = classifyMapper.insert(classify);
        if(num == 1){
            map.put("code",Const.SUCCESS_CODE);
            map.put("message","添加成功");
        }else {
            map.put("code",Const.ERROR_CODE);
            map.put("message","添加失败");
        }
        return map;
    }

    @Override
    public Map<String, Object> updateClassify(Classify classify) {
        Map<String,Object> map = new HashMap<>();
        map.put("label",classify.getLabel());
        List<Classify> list = classifyMapper.findByMap(map);
        map.clear();
        if(list.size() > 0){
            map.put("code",Const.ERROR_CODE);
            map.put("message","分类编号已存在");
            return map;
        }
        classify.setModifyTime(new Date());
        int num = classifyMapper.updateByPrimaryKeySelective(classify);
        if(num == 1){
            map.put("code",Const.SUCCESS_CODE);
            map.put("message","修改成功");
        }else {
            map.put("code",Const.ERROR_CODE);
            map.put("message","修改失败");
        }
        return map;
    }

    @Override
    public Map<String, Object> delClassify(Integer id) {
        Map<String,Object> map = new HashMap<>();
        int num = classifyMapper.deleteByPrimaryKey(id);
        if(num == 1){
            map.put("code",Const.SUCCESS_CODE);
            map.put("message","删除成功");
        }else {
            map.put("code",Const.ERROR_CODE);
            map.put("message","删除失败");
        }
        return map;
    }

    @Override
    public Map<String, Object> findUserConsumerMoney(String pageSize, String pageNum, Long userId, String startTime, String endTime, Integer type, Map<String, Object> map3) {
        Map<String, Object> map = new HashMap<>();
        map.put("orderType", type);
        map.put("orderState", 200);

        if (StringUtils.isEmpty(pageNum)) {
            pageNum = "1";
        }
        if (StringUtils.isEmpty(pageSize)) {
            pageSize = "10";
        }
        if (StringUtils.isNotEmpty(startTime)) {
            map.put("startTime", startTime);
        }
        if (StringUtils.isNotEmpty(endTime)) {
            map.put("endTime", endTime);
        }
        if (userId != 0) {
            map.put("userId", String.valueOf(userId));
        }

        String level = (String) map3.get("level");
        if (StringUtils.isEmpty(level)) {
            level = "0";
        }
        String area1 = (String) map3.get("area");
        String city1 = (String) map3.get("city");
        String province1 = (String) map3.get("province");
        switch (level) {
            case "1":
                String area2 = hatAreaMapper.findByAreaId(area1).getArea();
                String city2 = hatCityMapper.findByCityId(city1).getCity();
                String province2 = hatProvinceMapper.findByProvinceId(province1).getProvince();
                map.put("area", area2.substring(0, area2.length() - 1) + "%");
                map.put("city", city2.substring(0, city2.length() - 1) + "%");
                map.put("province", province2.substring(0, province2.length() - 1) + "%");
                break;
            case "2":
                String city3 = hatCityMapper.findByCityId(city1).getCity();
                String province3 = hatProvinceMapper.findByProvinceId(province1).getProvince();
                map.put("city", city3.substring(0, city3.length() - 1) + "%");
                map.put("province", province3.substring(0, province3.length() - 1) + "%");
                break;
            case "3":
                String province4 = hatProvinceMapper.findByProvinceId(province1).getProvince();
                map.put("province", province4.substring(0, province4.length() - 1) + "%");
                break;
            default:
        }

        PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        List<Order> list = orderMapper.findOrderList(map);
        PageInfo<Order> pageInfo = new PageInfo<>(list);
        List<Order> listOrder = pageInfo.getList();
        List<OrderVo> listVo = new ArrayList<>();
        for (Order o : listOrder) {
            OrderVo ov = new OrderVo();

            Long userIdTmp = o.getUserId();
            int pid = o.getProviderId();

            //买家信息
            UserInfo uiu = null;
            if (userIdTmp != null) {
                uiu = userInfoMapper.findUserById(userIdTmp);
            }

            //买家信息
            if (uiu != null) {
                ov.setUserId(uiu.getId());
                ov.setUserPhone(uiu.getPhone());
                ov.setUserRole(uiu.getRole());
            } else {
                ov.setUserId(null);
                ov.setUserPhone("");
                ov.setUserRole("");
            }

            //卖家信息
            UserInfo uir = null;
            if (pid != 0) {
                BusinessShop bs = businessShopMapper.selectByPrimaryKey((long) pid);
                Long userIdP = 0L;
                if (bs != null) {
                    userIdP = bs.getUserId();
                }
                if (userIdP > 0) {
                    uir = userInfoMapper.findUserById(userIdP);
                }
            }

            //卖家信息
            if (uir != null) {
                ov.setReceiveId(uir.getId());
                ov.setReceivePhone(uir.getPhone());
                ov.setShopName(uir.getNickName());
            } else {
                ov.setReceiveId(null);
                ov.setReceivePhone("");
                ov.setShopName("");
            }

            //下单时间
            ov.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(o.getCreateTime()));
            //订单类型
            ov.setTitle(new Byte(o.getOrderType().toString()));

            //消费金抵扣
            BigDecimal cmb = new BigDecimal(o.getDiscountPrice());
            if (cmb.compareTo(new BigDecimal("0")) > 0) {
                ov.setConsumerMoney(cmb.divide(new BigDecimal("100")));
            } else {
                ov.setConsumerMoney(new BigDecimal("0"));
            }

            //订单总金额
            BigDecimal dp = new BigDecimal(o.getDealPrice());
            if (dp.compareTo(new BigDecimal("0")) > 0) {
                ov.setDealPrice(dp.divide(new BigDecimal("100")));
            }else{
                ov.setDealPrice(new BigDecimal("0"));
            }

            listVo.add(ov);
        }
        map.clear();
        map.put("code", Const.SUCCESS_CODE);
        map.put("message", "查询成功");
        map.put("page", pageInfo);
        map.put("listVo", listVo);
        return map;
    }

    @Override
    @Transactional
    public Map<String, Object> updateIsPreferredBusiness(BusinessShopTemp businessShopTemp) {
        Map<String,Object> map = new HashMap<>();
        BusinessShopTemp businessShopTemp1 = businessShopTempMapper.selectByPrimaryKey(businessShopTemp.getId());
        if(null == businessShopTemp1){
            map.put("code",Const.ERROR_CODE);
            map.put("message","店铺不存在");
            return map;
        }
        if(businessShopTemp1.getState() != 1){
            map.put("code",Const.ERROR_CODE);
            map.put("message","店铺状态异常");
            return map;
        }
        int num = businessShopTempMapper.updateByPrimaryKeySelective(businessShopTemp);
        if(num != 1){
            map.put("code",Const.ERROR_CODE);
            map.put("message","修改失败");
            return map;
        }
        map.put("userId",businessShopTemp1.getUserId());
        BusinessShop businessShop = businessShopMapper.findByMap(map);
        if(null == businessShop){
            map.put("code",Const.ERROR_CODE);
            map.put("message","店铺不存在");
            return map;
        }
        if(businessShop.getState() != 1){
            map.put("code",Const.ERROR_CODE);
            map.put("message","店铺状态异常");
            return map;
        }
        businessShop.setIsPreferredBusiness(businessShopTemp.getIsPreferredBusiness());
        int num1 = businessShopMapper.updateByPrimaryKeySelective(businessShop);
        if(num1 == 1){
            map.put("code",Const.SUCCESS_CODE);
            map.put("message","修改成功");
        }else {
            throw new RuntimeException();
        }
        return map;
    }
}
